//
//  ScanQRcodeViewController.m
//  Logistics_Store
//
//  Created by 葛悦彣 on 2019/7/25.
//  Copyright © 2019 Air. All rights reserved.
//

#import "ScanQRcodeViewController.h"
#import <AVFoundation/AVFoundation.h>

static const char *ScanQRcodeName = "ScanQRcodeName";
static const char *VScanQRcodeName = "VScanQRcodeName";

@interface ScanQRcodeViewController ()<AVCaptureMetadataOutputObjectsDelegate,AVCaptureVideoDataOutputSampleBufferDelegate>

@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, strong) AVCaptureMetadataOutput *output;
@property (nonatomic, strong) AVCaptureDevice *captureDevice;

@property (nonatomic, strong) UIImageView * centerImg;
@property (nonatomic, strong) UIImage * img;
@property (nonatomic, strong) NSString * code;

@property (nonatomic, assign) BOOL isImg;
@property (nonatomic, strong) UIButton * openSGDBtn;

@end

@implementation ScanQRcodeViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}
//扫描二维码
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"扫一扫";
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];          //读取设备授权状态
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        
        NSDictionary *mainInfoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [mainInfoDictionary objectForKey:@"CFBundleDisplayName"];
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"请在\"设置-隐私-相机\"选项中，允许%@访问你的手机相机", appName]
                                                                       message:@""
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
            [self.navigationController popViewControllerAnimated:YES];
            
            NSURL *url= [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if( [[UIApplication sharedApplication]canOpenURL:url] ) {
                [[UIApplication sharedApplication]openURL:url];
            }
            
            
            
        }];
        UIAlertAction* defaultAction2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                               handler:^(UIAlertAction * action) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [alert addAction:defaultAction];
        [alert  addAction:defaultAction2];
        [self presentViewController:alert animated:YES completion:nil];
    } else {
        // 开启扫描
        [self startScan];
        //    [self createBackView];
        [self animateineAction];
        MJWeakSelf
        UIView * backbtn = [UIView new].addClickBlock(^{
            [weakSelf popViewController];
        });
        backbtn.backgroundColor = KcolorHex(@"#00000066");
        [DTKTool YJ:kwt(15) andView:backbtn];
        [self.view addSubview:backbtn];
        [backbtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(kwt(40));
            make.left.offset(kwt(20));
            make.width.height.offset(kwt(30));
        }];
        UIImageView * img = kimageView(@"close_icon");
        [backbtn addSubview:img];
        [img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.bottom.offset(0);
        }];
        UIButton * openSGD = [UIButton buttonWithType:0];
        [openSGD setImage:[UIImage imageNamed:@"flashlight"] forState:UIControlStateNormal];
        [openSGD setImage:[UIImage imageNamed:@"flashlight1"] forState:UIControlStateSelected];
        self.openSGDBtn = openSGD;
        [self.view addSubview:openSGD];
        [openSGD mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.offset(kwt(-40) - KSafeAreaBottomHeight);
            make.right.offset(kwt(-40));
            make.width.height.offset(kwt(42));
        }];
        openSGD.addTarget(self,@selector(openSGD));
        UILabel * tempLab = [DTKTool labelWithText:@"请扫描池塘二维码" andFont:kFont(19) andTextColor:UIColor.whiteColor];
        [self.view addSubview:tempLab];
        tempLab.textAlignment = NSTextAlignmentCenter;
        tempLab.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        [DTKTool YJ:kwt(21) andView:tempLab];
        [tempLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.offset(kwt(-40) - KSafeAreaBottomHeight);
            make.right.offset(kwt(-98));
            make.height.offset(kwt(42));
            make.width.offset(kwt(240));
        }];
        //监听后台化
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    }
    
}


///闪光灯
- (void)openSGD{
    NSLog(@"%ld",(long)self.captureDevice.torchMode);
    if(self.captureDevice.torchMode == 0){
        [self.captureDevice lockForConfiguration:nil];
        [self.captureDevice setTorchMode: AVCaptureTorchModeOn];//开
        [self.captureDevice unlockForConfiguration];
        self.openSGDBtn.selected = YES;
    } else {
        [self.captureDevice lockForConfiguration:nil];
        [self.captureDevice setTorchMode: AVCaptureTorchModeOff];//关
        [self.captureDevice unlockForConfiguration];
        self.openSGDBtn.selected = NO;
    }
    
}
//创建蒙版与4个角
- (void)createBackView{
    //    UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.view.bounds];
    //
    //    [path moveToPoint:CGPointMake(kwt(67.5), kwt(187))];
    //    [path addLineToPoint:CGPointMake(kwt(307.5), kwt(187))];
    //    [path addLineToPoint:CGPointMake(kwt(307.5), kwt(427))];
    //    [path addLineToPoint:CGPointMake(kwt(67.5), kwt(427))];
    //    [path addLineToPoint:CGPointMake(kwt(67.5), kwt(187))];
    //    path.usesEvenOddFillRule = YES;
    //
    //    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    //    shapeLayer.path = path.CGPath;
    //    shapeLayer.fillColor= [UIColor blackColor].CGColor;  //其他颜色都可以，只要不是透明的
    //    shapeLayer.fillRule=kCAFillRuleEvenOdd;
    //
    //    UIView *translucentView = [UIView new];
    //    translucentView.frame = self.view.bounds;
    //    translucentView.backgroundColor = [UIColor blackColor];
    //    translucentView.alpha = 0.5;
    //    translucentView.layer.mask = shapeLayer;
    //
    //    [self.view addSubview:translucentView];
    
    
    CGFloat imgLeftX = kwt(30);
    CGFloat imgTopY = kwt(135);
    CGFloat imgW = kwt(315);
    CGFloat imgH = kwt(262);
    //添加图片
    UIImageView * leftTopimg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"GBJL_ScanBack"]];
    leftTopimg.frame = CGRectMake(imgLeftX,imgTopY, imgW, imgH);
    [self.view addSubview:leftTopimg];
    
    UILabel * tltle = [DTKTool labelWithText:@"扫一扫识别条形码" andFont:kFont(16) andTextColor:KcolorHex(@"#222222")];
    [self.view addSubview:tltle];
    [tltle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.bottom.offset(kwt(-100));
    }];
    
}
#pragma mark -- 开始扫描
- (BOOL)startScan {
    // 获取手机硬件设备
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    self.captureDevice = captureDevice;
    // 初始化输入流
    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@",[error localizedDescription]);
        return NO;
    }
    // 创建会话
    _captureSession = [[AVCaptureSession alloc] init];
    // 添加输入流
    [_captureSession addInput:input];
    // 初始化输出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    //识别范围,比框的范围略大
    CGSize size = self.view.bounds.size;
    CGRect cropRect = CGRectMake(kwt(20),kwt(130),kwt(335),kwt(280));
    output.rectOfInterest =  CGRectMake(cropRect.origin.y/SCREEN_HEIGHT,
                                        cropRect.origin.x/size.width,
                                        cropRect.size.height/size.height,
                                        cropRect.size.width/size.width);
    
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    self.output = output;
    // 添加输出流
    [_captureSession addOutput:output];
    AVCaptureVideoDataOutput * videoOutput = [[AVCaptureVideoDataOutput alloc] init];
    videoOutput.alwaysDiscardsLateVideoFrames = YES;
    videoOutput.videoSettings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey];
    
    // 创建dispatch queue
    dispatch_queue_t queue = dispatch_queue_create(ScanQRcodeName, DISPATCH_QUEUE_CONCURRENT);
    //扫描的结果苹果是通过代理的方式区回调，所以outPut需要添加代理，并且因为扫描是耗时的工作，所以把它放到子线程里面
    [output setMetadataObjectsDelegate:self queue:queue];
    [videoOutput setSampleBufferDelegate:self queue:queue];
    [_captureSession addOutput:videoOutput];
    // 设置支持二维码和条形码扫描
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeEAN13Code]];
    // 创建输出对象
    _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    _previewLayer.frame = self.view.bounds;
    [self.view.layer insertSublayer:_previewLayer atIndex:0];
    // 开始会话
    [_captureSession startRunning];
    
    return YES;
}

// 结束扫描
- (void)stopScan {
    // 停止会话
    [_captureSession stopRunning];
    _captureSession = nil;
}
- (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
    
    if(self.code){
        UIImage * img = [self imageFromSampleBuffer2:sampleBuffer];
        [self stopScan];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.ScanPopandImgBlock(self.code,img);
            [self.navigationController popViewControllerAnimated:YES];
        });
    }
}
- (UIImage *)imageFromSampleBuffer2:(CMSampleBufferRef)sampleBuffer {
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    CIImage *ciImage = [CIImage imageWithCVPixelBuffer:imageBuffer];
    CIContext *temporaryContext = [CIContext contextWithOptions:nil];
    CGImageRef videoImage = [temporaryContext createCGImage:ciImage fromRect:CGRectMake(0, 0, CVPixelBufferGetWidth(imageBuffer), CVPixelBufferGetHeight(imageBuffer))];
    
    UIImage *image = [[UIImage alloc] initWithCGImage:videoImage scale:1 orientation:UIImageOrientationRight];
    CGImageRelease(videoImage);
    return image;
}
#pragma mark -- AVCaptureMetadataOutputObjectsDelegate
// 扫描结果的代理回调方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if (metadataObjects != nil && metadataObjects.count > 0) {
        
        // 获取结果并对其进行处理
        AVMetadataMachineReadableCodeObject *object = metadataObjects.firstObject;
        if ([[object type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            NSString *result = object.stringValue;
            // 处理result
            NSLog(@"%@",result);
            //            字符串转字典
            NSDictionary * dict = [DTKTool dictionaryWithJsonString:result];
            if([[dict allKeys] containsObject:@"id"] && [[dict allKeys] containsObject:@"type"] ){
                int type = [NSString stringWithFormat:@"%@",[dict objectForKey:@"type"]].intValue;
                if(type == 1){
                    result = [dict objectForKey:@"id"];
                } else {
                    return;
                }
            } else {
                return;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self stopScan];

                if (self.ScanBlock) {
                    self.ScanBlock(result);

//                    [self.navigationController popViewControllerAnimated:YES];
//                    NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
//                    for (UIViewController *vc in marr) {
//                        if (vc == self) {
//                            [marr removeObject:vc];
//                            break;          //break一定要加，不加有时候有bug
//                        }
//                    }
//                    self.navigationController.viewControllers = marr;
                }
                if(self.ScanPopandImgBlock){
                    self.code = result;
                    return;
                }
                if(self.NewScanBlock){
                    self.NewScanBlock(result);
                }else{
                    [self loadScanQRCode:result];
                }
                [self stopScan];
                
            });
//        } else if([[object type] isEqualToString:AVMetadataObjectTypeCode128Code] || [[object type] isEqualToString:AVMetadataObjectTypeEAN13Code]){
//            NSLog(@"是条形码");
//            NSString *result = object.stringValue;
//            // 处理result
//            NSLog(@"%@",result);
//            NSDictionary * dict = [DTKTool dictionaryWithJsonString:result];
//            if([[dict allKeys] containsObject:@"id"] && [[dict allKeys] containsObject:@"type"] ){
//                int type = [NSString stringWithFormat:@"%@",[dict objectForKey:@"type"]].intValue;
//                if(type == 1){
//                    result = [dict objectForKey:@"id"];
//                } else {
//                    return;
//                }
//            } else {
//                return;
//            }
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                if (self.ScanBlock) {
//                    self.ScanBlock(result);
////                    [self.navigationController popViewControllerAnimated:YES];
//                    NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
//                    for (UIViewController *vc in marr) {
//                        if (vc == self) {
//                            [marr removeObject:vc];
//                            break;          //break一定要加，不加有时候有bug
//                        }
//                    }
//                    self.navigationController.viewControllers = marr;
//                }
//                if(self.ScanPopandImgBlock){
//                    self.code = result;
//                    return;
//                }
//                if(self.NewScanBlock){
//                    self.NewScanBlock(result);
//                }
//                [self stopScan];
//            });
        }
    }
}

#pragma mark -- 扫描接口

/**
 根据二维码访问接口
 
 @param CodeStr 返回的接口
 */
- (void)loadScanQRCode:(NSString *)CodeStr{
    NSDictionary * dict = [self dictionaryWithJsonString:CodeStr];
    if(dict == nil){
        return;
    }
    
}


-(void)show{
    self.ScanEndBlock();
    [self.navigationController popViewControllerAnimated:NO];
}


#pragma mark -- 执行动画

- (void)animateineAction {
    
    if (!_centerImg) {
        _centerImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"GBJL_ScanLine"]];
        _centerImg.frame = CGRectMake(kwt(20), kwt(135), kwt(335), kwt(30));
        [self.view addSubview:_centerImg];
        
    }
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:_centerImg.center];
    [path addLineToPoint:CGPointMake(kwt(187.5), kwt(400))];
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    pathAnimation.path = path.CGPath;
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.animations = @[pathAnimation];
    animationGroup.duration = 2; //设置动画执行时间；这里设置为1.0秒
    animationGroup.repeatCount = 1000;//重复
    [_centerImg.layer addAnimation:animationGroup forKey:nil];
}
- (void)applicationWillEnterForeground{
    //后台化后重新执行动画
    [self.centerImg.layer removeAllAnimations];
    [self animateineAction];
}

#pragma mark -- 字符串转模型
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


- (void)dealloc {
    [self stopScan];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
